import 'dart:async';
import 'dart:convert';
import 'dart:io' show Platform;

import 'package:submail_one_login_flutter/model/login_access_code_model.dart';

import 'model/login_token_model.dart';
import 'submail_one_login_plugin_platform_interface.dart';

class SubPlatformConfig {
  String appId;
  String appKey;

  SubPlatformConfig({required this.appId, required this.appKey});
}

class SubSDK {
  static Future<(bool success, String? result)> init({
    SubPlatformConfig? androidConfig,
    SubPlatformConfig? iosConfig,
    bool debug = false,
    int timeout = 60,
  }) async {
    if (Platform.isAndroid) {
      assert(androidConfig != null, "androidConfig is null");
    }
    if (Platform.isIOS) {
      assert((iosConfig != null), "iosConfig is null");
    }

    var res = await SubmailOneLoginPluginPlatform.instance.init(
      androidConfig: androidConfig,
      iosConfig: iosConfig,
      debug: debug,
      timeout: timeout,
    );
    print("res: ${res.runtimeType}");
    if (res == null || res is! Map) {
      return (false, "");
    }
    final success = res['success'] as bool;
    return (success, res['result'] as String);
  }

  static Future<(bool success, LoginAccessCodeModel? result)>
      getLoginAccessCode() async {
    var res = await SubmailOneLoginPluginPlatform.instance.getLoginAccessCode();
    if (res == null || res is! Map) {
      return (false, null);
    }

    final success = res['success'] as bool;
    var data = LoginAccessCodeModel.fromJson(jsonDecode(res['result']));
    return (success, data);
  }

  static Future<(bool success, LoginTokenModel? result)> getLoginToken() async {
    final res = await SubmailOneLoginPluginPlatform.instance.getLoginToken();
    if (res == null || res is! Map) {
      return (false, null);
    }

    final success = res['success'] as bool;
    var data = LoginTokenModel.fromJson(jsonDecode(res['result']));
    return (success, data);
  }

  static FutureOr close() => SubmailOneLoginPluginPlatform.instance.close();

  /// [getNetworkType] 获取⽹络状态和运营商类型
  /// ⽹络类型：0-未知、1-数据流量、2-纯WiFi、3-流量+WiFi
  static Future<int?> getNetworkType() async {
    return await SubmailOneLoginPluginPlatform.instance.getNetworkType();
  }

  /// [getOperatorType] 获取⽹络状态和运营商类型
  /// 运营商类型：0-未知；1-移动；2-联通；3-电信
  static Future<int?> getOperatorType() async {
    return await SubmailOneLoginPluginPlatform.instance.getOperatorType();
  }

  static Future<void> delScrip() async {
    return await SubmailOneLoginPluginPlatform.instance.delScrip();
  }

  static Future<dynamic> getPhoneNumber() async {
    return await SubmailOneLoginPluginPlatform.instance.getPhoneNumber();
  }
}
